﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Flags]
public enum EVENT_TYPE {
    PLAYING=1<<1,
    GAME_INIT=1<<2,
    REPALY=1<<3,
    PAUSE=1<<4,
    GAME_OVER=1<<5,
    MENU=1<<6,
    SETTING=1<<7
}

public class EventManager : BaseManager<EventManager> {

    #region 委托事件管理
    /// <summary>
    /// EventManager所管理的委托事件
    /// </summary>
    /// <param name="Event_Type">事件种类</param>
    /// <param name="Sender">发送信号的组件</param>
    /// <param name="Param">其余参数</param>
    public delegate void OnEvent(EVENT_TYPE Event_Type,
        Component Sender, object Param = null);

    private Dictionary<EVENT_TYPE, List<OnEvent>> Listeners
        = new Dictionary<EVENT_TYPE, List<OnEvent>>();

    #endregion

    #region 函数

    /// <summary>
    /// 添加监听者
    /// </summary>
    /// <param name="Event_Type">事件种类</param>
    /// <param name="Listener">监听者函数</param>
    public void AddListener(EVENT_TYPE Event_Type,OnEvent Listener)
    {
        List<OnEvent> ListenList = null;
        if(Listeners.TryGetValue(Event_Type,out ListenList))
        {
            ListenList.Add(Listener);
            return;
        }
        ListenList = new List<OnEvent>();
        ListenList.Add(Listener);
        Listeners.Add(Event_Type,ListenList);
    }

    /// <summary>
    /// 调用所有Event_Type类型的函数
    /// </summary>
    public void PostNotification(EVENT_TYPE Event_Type,Component Sender,
        object Param=null)
    {
        List<OnEvent> ListenList = null;
        if (!Listeners.TryGetValue(Event_Type, out ListenList))
            return;
        foreach(OnEvent e in ListenList)
        {
            e(Event_Type, Sender, Param);
        }
    }

    public void RemoveEvent(EVENT_TYPE Event_Type)
    {
        Listeners.Remove(Event_Type);
    }

    public void RemoveRedundancies()
    {
        Dictionary<EVENT_TYPE, List<OnEvent>> tmpListeners
            = new Dictionary<EVENT_TYPE, List<OnEvent>>();
        foreach(KeyValuePair<EVENT_TYPE,List<OnEvent>> Item in Listeners)
        {
            for(int i=Item.Value.Count-1;i>=0;i--)
            {
                if(Item.Value[i].Equals(null))
                {
                    Item.Value.RemoveAt(i);
                }
            }
            if (Item.Value.Count > 0)
            {
                tmpListeners.Add(Item.Key, Item.Value);
            }
        }
        Listeners = tmpListeners;
    }

    private void OnLevelWasLoaded(int level)
    {
        RemoveRedundancies();
    }

    protected override void OnMyEvent(EVENT_TYPE Event_Type, Component Sender, object Param = null)
    {
        
    }

    #endregion


}
